//
//  SourceListItem.m
//  PXSourceList
//
//  Created by Alex Rozanski on 08/01/2010.
//  Copyright 2010 Alex Rozanski http://perspx.com
//
//  GC-enabled code revised by Stefan Vogt http://byteproject.net
//

#import "SourceListItem.h"
#import "GBall.h"
#import "GBTableColumnHeader_position_bottom_sumaverage.h"
@implementation SourceListItem

@synthesize tableobject;
@synthesize title;
@synthesize identifier;
@synthesize icon;
@synthesize badgeValue;
@synthesize children;
@synthesize paraent;
@synthesize isUseForGroup;
@synthesize treeNode_self; 


#pragma mark -
#pragma mark Init/Dealloc/Finalize

- (id)init
{
	if(self=[super init])
	{
		//初始值
        badgeValue = @"";	//We don't want a badge value by default
	    paraent=nil;
        isUseForGroup=[NSNumber numberWithBool: NO];   //初始值不當作資料夾使用        
        
        //子物件陣列實體化
        children=[[NSMutableArray alloc] init];         
        
        //存放報價表上的資料
        tableobject=[[PXTableObject alloc] init];
        
    }
	
	return self;
}

 

+ (id)itemWithTitle:(NSString*)aTitle identifier:(NSString*)anIdentifier
{	
	
    SourceListItem *item = [SourceListItem itemWithTitle:aTitle identifier:anIdentifier icon:nil];
	
	return item;
}


+ (id)itemWithTitle:(NSString*)aTitle identifier:(NSString*)anIdentifier icon:(NSString*)anIcon
{
	SourceListItem *item = [[[SourceListItem alloc] init] autorelease];
    
	[item setTitle:NSLocalizedString(aTitle, aTitle)];
	[item setIdentifier:anIdentifier];
	[item setIcon:anIcon];
	
	return item;
}
#pragma mark -
#pragma mark NSCoder
 
 


- (void)encodeWithCoder:(NSCoder *)aCoder{
    
    [aCoder encodeObject:title forKey:@"SourceListItem_title"]; 
    [aCoder encodeObject:identifier forKey:@"SourceListItem_identifier"];   
    [aCoder encodeObject:icon forKey:@"SourceListItem_icon"]; 
    [aCoder encodeObject:paraent forKey:@"SourceListItem_paraent"];    
    
    [aCoder encodeObject:children forKey:@"SourceListItem_children"]; 
    [aCoder encodeObject:tableobject forKey:@"SourceListItem_tableobject"];
    [aCoder encodeObject:isUseForGroup forKey:@"SourceListItem_isUseForGroup"]; 
    [aCoder encodeObject: badgeValue forKey:@"SourceListItem_badgeValue"];    
    
}
- (id)initWithCoder:(NSCoder *)aDecoder{
    self=[super init];
    if (self) {
        title=[[aDecoder decodeObjectForKey:@"SourceListItem_title"] retain]; 
        identifier=[[aDecoder decodeObjectForKey:@"SourceListItem_identifier"] retain]; 
        icon=[[aDecoder decodeObjectForKey:@"SourceListItem_icon"] retain]; 
        paraent=[[aDecoder decodeObjectForKey:@"SourceListItem_paraent"] retain]; 
        children=[[aDecoder decodeObjectForKey:@"SourceListItem_children"] retain]; 
        tableobject=[[aDecoder decodeObjectForKey:@"SourceListItem_tableobject"] retain]; 
        isUseForGroup=[[aDecoder decodeObjectForKey:@"SourceListItem_isUseForGroup"] retain]; 
        badgeValue=[[aDecoder decodeObjectForKey: @"SourceListItem_badgeValue"] retain] ; 
        
        
    }
    return self;
}



#pragma mark -
#pragma mark 取的資料模型參考位置
/*
-(void)set_Data_model:(Data_Model *)dml{
   
    datamodel_SLI=dml;
    
}
*/


#pragma mark -
#pragma mark dealloc/finalize
- (void)dealloc
{
	[title release];
	[identifier release];
	[icon release];
	
    [children release];
	[tableobject release];
    
	[super dealloc];
}

- (void)finalize
{
	title = nil;
	identifier = nil;
	icon = nil;
	children = nil;
	tableobject=nil;
    
	[super finalize];
}

#pragma mark -
#pragma mark 回報是否值

//是否有超過一個以上的子節點當作判斷
- (BOOL)hasChildren
{
	 
    return [children count]>0;
     
    
}
//以是否有連結母親
- (BOOL)hasParent{
    if (paraent==nil) {
        return NO;
    }
    else{
        return YES;
    
    }
}

- (BOOL)hasIcon
{
	return icon!=nil;
}

//小於0
- (BOOL)hasBadge
{
	return ![badgeValue isEqualToString:@""];
}


#pragma mark -
#pragma mark 設定母子關係

//表示從母親的角度來看,自己是排序第幾個
-(NSInteger)inexparent{
    if ([paraent children] !=nil) {
        return [[paraent children] indexOfObject:self ];
    }
    else{
        return -1;
    }
}

- (void)addChid:(SourceListItem *)ch{
    
    [children addObject:ch];
    
}

//原理：就是透過檢查是否有上一層母親，如果有，就繼續往上一層
- (SourceListItem *)get_TopParaent{
    if ([paraent retainCount]>0) {
       // NSLog(@"get_TopParaent yes");
        //再度往上一層的循環
        return  [paraent get_TopParaent];        
    }
    else{
        //直到已經沒有母親了就傳回自已
       // NSLog(@"get_TopParaent no");  
        return self;        
        
    }
    
}




//取出涵蓋自己到最上層所有的node 節點資料
/* 使用方法
   1.先建立一個存放的記憶體
   NSMutableArray *all_node=[[NSMutableArray alloc] init];
   
   2.找到要向上搜尋的結點
   [selectnode get_ALLParaent:all_node];
   
   3.取出所有節點位置資料
   for (SourceListItem *upnode in all_node  ) {
     NSLog(@"popUpAction=%@",  [upnode title ] );
   }
*/
- (SourceListItem *)get_ALLParaent:(NSMutableArray *)all_parent{
    
    
    
    if ([paraent retainCount]>0) {
        //該節點有資料
        if (all_parent) {
            [all_parent addObject:self];
        }
        //再度往上一層的循環
        return  [paraent get_ALLParaent:all_parent];
    }
    else{
        //直到已經沒有母親了就傳回自已
        // NSLog(@"get_TopParaent no");
        return self;
        
    }



}
#pragma mark -
#pragma mark 樹狀結構的各個資料統計

//功能步驟：樹狀排序 功能步驟: 7.2.顯示樹狀列最右邊的小圈點

-(void)update_TableCalcuate:(NSMutableDictionary *)sort_data{
    //標記：樹狀結構的各個資料統計  實作方法    
    
    //表示進入排序階段
    if (sort_data!=nil && sort_data) {
        //排序方法：名稱
        if ([[sort_data objectForKey:key_sort_name] isEqualToString:_sort_by_name] ) {
            
            //表示有自選股名單物件
            if ([tableobject retainCount]>0) {
                
                //有自選股名單代碼物件
                if([[tableobject data_array_object] retainCount]>0){
                    
                    if ([[tableobject data_array_object] count]>0) {
                        
                        
                        [self setBadgeValue:[NSString stringWithFormat:@"%@=%@",NSLocalizedString(@"Sort_Name", @"名稱"), title]];
                    }
                    else{
                        
                        [self setBadgeValue:@""];
                    }
                }
                
                
                
            }
        }
        //排序方法：檔數
        else  if ([[sort_data objectForKey:key_sort_name] isEqualToString:_sort_by_count] ) {
            
            //表示有自選股名單物件
            if ([tableobject retainCount]>0) {
                
                //有自選股名單代碼物件
                if([[tableobject data_array_object] retainCount]>0){
                    
                    if ([[tableobject data_array_object] count]>0) {
                        
                        NSString *fg=[NSString stringWithFormat:@"%@=%ld",NSLocalizedString(@"Sort_Count", @"檔數"),[[tableobject data_array_object] count]];
                        [self setBadgeValue:fg ];
                    }
                    else{
                        
                        [self setBadgeValue:@""];
                    }
                }
                
                
                
            }

        }
        //排序方法：其他 技術指標訊號
        else{
            //進入排序階段
            
            //表示有自選股名單物件
            if ([tableobject retainCount]>0) {
                
                double a;
                a= [[[tableobject data_dic_onlyfortableObject] objectForKey:[sort_data objectForKey:key_sort_name_method]] doubleValue]  ;
                
                [self setBadgeValue:[NSString stringWithFormat:@"%@(%@)=%g",NSLocalizedString([sort_data objectForKey:key_sort_name], @"name") ,NSLocalizedString([sort_data objectForKey:key_sort_method], @"method"), a]];
                
            }
        
        }
                 
    }
    //表示非排序階段
    else {
        //表示有自選股名單物件
        if ([tableobject retainCount]>0) {
            
            //有自選股名單代碼物件
            if([[tableobject data_array_object] retainCount]>0){   
                
                if ([[tableobject data_array_object] count]>0) {
                    
                    
                    
                    [self setBadgeValue:[NSString stringWithFormat:@"%ld", [[tableobject data_array_object] count]]];
                    
                }
                else{
                    
                    [self setBadgeValue:@""];
                    
                }
            }
            
            
            
        }
        
        
        
    }
    
      
}
 
#pragma mark -
#pragma mark Custom Accessors

- (NSString *)description
{
	    
    return [NSString stringWithFormat:@"%@ = %p | identifier = %@ | title = %@  | indexpath = %ld   ", [self class], self, self.identifier, self.title,[self inexparent]];
}



//將代碼陣列加入整個dataarrayobject
-(void)set_arraycode_to_data_array_object:(NSMutableArray *)codearray set_Data_model:(Data_Model *)dml  {
    //此段程式會先找Data_Objec有沒有已經有子物件，如果沒有就產生，並且將此子物件加到tableobject data_array_object    
     
   // if ([[self isUseForGroup ]isEqualToNumber:[NSNumber numberWithBool:NO]]){    
       [codearray retain];
        
    
        //1.清除data_array_object 
        [[tableobject data_array_object] removeAllObjects]; 
        
        //2.逐一加入到
        for (NSMutableDictionary *md in codearray  ) {
                        
            //先取得資料物件的參考位置
            Data_Object *get_dataobject=[dml add_data_object_dic_data:  md];
            
            //加入參考位置
            [[tableobject data_array_object] addObject:get_dataobject];        
            
        }
        
        
        
    
   // }
          
}

-(NSMutableArray *)get_allcode_from_data_array_object{
    NSMutableArray *temp=[[NSMutableArray alloc] init];
    
    for (Data_Object * dos in [tableobject data_array_object] ) {
    
        [temp addObject:[dos table_data]];        
    }        
    
    [temp autorelease];
    return temp;
}

//SortTableview
-(void)sort_TableObjet_Data_Object_Array:(NSMutableDictionary *)sort_field{
    
  
    
    NSString *sort_name=[sort_field objectForKey:key_sort_name];
    NSString *sort_updown=[sort_field objectForKey:key_sort_upordown];
    
    NSLog(@"節點內部進行排序 排序方法=%@ 排序方向=%@",sort_name,sort_updown);    
    
    
    //排序實作方法
    
    NSArray *sortedArray = [[ self children ] sortedArrayUsingComparator:^(id firstObject, id secondObject) {
        /*
        //字串比較
        NSString *lastName1 = [(SourceListItem *)firstObject  title];
        NSString *lastName2 = [(SourceListItem *)secondObject title];
        
        return [lastName1 caseInsensitiveCompare:lastName2];
        */
        
        if ([sort_name isEqualToString:_sort_by_count]) {
            
            //數字比較
            NSNumber *lastName1 =[NSNumber numberWithInteger: [[[(SourceListItem *)firstObject  tableobject] data_array_object] count]];
            NSNumber *lastName2 = [NSNumber numberWithInteger: [[[(SourceListItem *)secondObject  tableobject] data_array_object] count]];
            
            
            
            if ([sort_updown isEqualToString:@"up"]) {
                return [lastName1 compare:lastName2];   
            }
            else {
                return [lastName2 compare:lastName1];     
            }
            
            
        }
        else if ([sort_name isEqualToString:_sort_by_name]) {
          ;
           
                       
            
            //文字比較
            NSString *lastName1 = [(SourceListItem *)firstObject  title];
            NSString *lastName2 = [(SourceListItem *)secondObject title];
           
            
            if ([sort_updown isEqualToString:@"up"]) {
                return [lastName1 caseInsensitiveCompare:lastName2];   
            }
            else {
               return [lastName2 caseInsensitiveCompare:lastName1];    
            }
            
            
        }
        else  {
            
            //數字比較
            NSNumber *lastName1 =  [ [ [(SourceListItem *)firstObject tableobject] data_dic_onlyfortableObject] objectForKey:[sort_field objectForKey:key_sort_name_method]];
            NSNumber *lastName2 =   [ [ [(SourceListItem *)secondObject tableobject] data_dic_onlyfortableObject] objectForKey:[sort_field objectForKey:key_sort_name_method]];
            
            
            
            if ([sort_updown isEqualToString:@"up"]) {
                return [lastName1 compare:lastName2];   
            }
            else {
                return [lastName2 compare:lastName1];     
            }
            
        }        
        
                           
        
    }];
    
    //設定新的排序陣列 
    [self setChildren:[[sortedArray mutableCopy] autorelease]];     
    
    
      
}


@end
